package com.cskaoyan.shopping.api;

import com.cskaoyan.mall.commons.result.ServiceCallResponse;
import com.cskaoyan.mall.commons.result.ServiceCallResponseUtil;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemServiceResponse;
import com.cskaoyan.mall.dto.ProductDetailDto;
import com.cskaoyan.mall.dto.ProductDetailServiceResponse;
import com.cskaoyan.shopping.dto.CartProductDto;
import com.cskaoyan.shopping.service.IProductService;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @auther cskaoyan
 * @date 2022/8/24:14:56
 */
@RestController
public class OrderApiImpl {

    @Autowired
    IProductService productService;

/*    @Autowired
    RedissonClient redissonClient;*/

    @GetMapping(value = "/rpc/product/detail")
    ServiceCallResponse<ProductDetailDto> getProductDetail(@RequestParam("id") Long id) {
        ProductDetailDto productDetail = productService.getProductDetail(id);
        ServiceCallResponseUtil<ProductDetailDto> responseUtil = new ServiceCallResponseUtil<>();
        return responseUtil.ok(productDetail);
    }


    /**
     * 根据用户id和productId
     * 帮助订单删除购物车中的订单商品
     *
     * @param request
     * @return
     */

    @PostMapping(value = "/rpc/cart/items")
    ClearCartItemServiceResponse clearCartItemByUserID(@RequestBody ClearCartItemRequest request) {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://localhost:6379");
        RedissonClient redissonClient = Redisson.create(config);

        Long userId = request.getUserId();         //用户id
        Map<String, CartProductDto> map = redissonClient.getMap(userId.toString());  //从Redis里拿到这个用户id的Map


        for (Long productId : request.getProductIds()) {     //遍历要删除的商品id
            for (Map.Entry<String, CartProductDto> stringCartDtoEntry : map.entrySet()) {
                if ((productId == Long.parseLong(stringCartDtoEntry.getKey())) ) {         //遍历、如果匹配到Redis里的goodId(就是key！！！）则删除
                    map.remove(stringCartDtoEntry.getKey());                        //把这个productId的键值对删掉
                }
            }
        }
        return null;
    }
}
